package com.atguigu.aclservice.service.impl;

import com.atguigu.aclservice.entity.Role;
import com.atguigu.aclservice.entity.UserRole;
import com.atguigu.aclservice.entity.vo.AssginRoleVo;
import com.atguigu.aclservice.mapper.RoleMapper;
import com.atguigu.aclservice.mapper.UserRoleMapper;
import com.atguigu.aclservice.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author fxy
 * @since 2022-10-27
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    //获取用户的角色数据
    @Override
    public Map<String, Object> getRolesByUserId(String userId) {
        //获取所有角色
        List<Role> roles = baseMapper.selectList(null);
        //根据用户id查询，已经分配角色
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<UserRole> userRolesList = userRoleMapper.selectList(wrapper);
        //从userRoles集合获取所有角色id
        List<Long> userRoleIds = new ArrayList<>();
        for (UserRole userRole : userRolesList) {
            Long roleId = (userRole.getRoleId());
            userRoleIds.add(roleId);
        }
        //封装到map集合
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("allRoles",roles);//所有角色
        returnMap.put("userRoleIds",userRoleIds);//用户分配角色id集合
        return returnMap;
    }

    //用户分配角色
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        //根据用户id删除之前分配角色
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",assginRoleVo.getUserId());
        userRoleMapper.delete(wrapper);
        //获取所有角色id，添加角色用户关系表
        //角色id列表
        List<String> roleIdList = assginRoleVo.getRoleIdList();
        for (String roleId:roleIdList) {
            UserRole userRole = new UserRole();
            userRole.setUserId(Long.valueOf(assginRoleVo.getUserId()));
            userRole.setRoleId(Long.valueOf(roleId));
            userRoleMapper.insert(userRole);
        }
    }
}
